//
//  SYCollectionView.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/4/12.
//  Copyright © 2019年 李文强. All rights reserved.
//

#import "SYCollectionView.h"
#import "SYFunctionCollectionViewCell.h"
#import "SYNewAlerView.h"
#import "SYMobileView.h"
#import "SYPlayerViewController.h"
#import "SYWordViewController.h"
#import "SYPPTViewController.h"
#import "GFWebViewController.h"
#import "WXApiObject.h"
#import "WXApi.h"
//#import "SYInteractionViewController.h"


@interface SYCollectionView () <UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate,SYFunctionCollectionViewCellDelegate>
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) UIViewController *contentVC;
@property (strong, nonatomic) SYNewAlerView *alerView;
@property (strong, nonatomic) SYMobileView *mobileView;
@property (strong, nonatomic) SYCollectionModel *selectModel;//选中需要操作的model
@property (strong, nonatomic) NSString *path;
@property (strong, nonatomic) NSString *sharePath;

@property (nonatomic, copy) NSString *detailShareStr;


@end


@implementation SYCollectionView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.dataArr = [NSMutableArray array];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}
-(void)setViewIsFrom:(NSString *)isfrom{
    self.isFrom = isfrom;
}
- (void)subUpViewArr:(NSMutableArray *)dataArr vc:(UIViewController *)vc WithIsFrom:(NSString *)isFrom{
    self.isFrom = isFrom;
    self.dataArr = dataArr;
    self.contentVC = vc;
    [self initSubView];
    
}

- (void)initSubView {
    
   
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.equalTo(self);
    }];
    
    
    [self.collectionView reloadData];
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        //自动网格布局
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, CGRectGetHeight(self.frame)) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"SYFunctionCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SYFunctionCollectionViewCell"];
         [self addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SYFunctionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SYFunctionCollectionViewCell" forIndexPath:indexPath];
    cell.model = self.dataArr[indexPath.row];
    cell.status = self.stant;
    [cell functionCollectionModel:self.dataArr[indexPath.row]
                        indexPath:indexPath
                        setIsChar:self.isChar
                           isFrom:self.isFrom];
    cell.delegate = self;
    return cell;
}
/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(125, 174);
}
/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(50, 40, 50, 40);
    
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 50;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 40;
}
/**
 点击了某个item
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
//    SYChildViewController *childVC = [[SYChildViewController alloc] init];
    
    
    SYCollectionModel *model = self.dataArr[indexPath.row];
    
    if (self.isChar) {//聊天辅导进入
        
        if ([model.type isEqualToString:@"4"]) {//如果是ppt就进行处理
            model.downLoadPath =  [model.downLoadPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [self isLoading:model.downLoadPath];
        } else if ([model.type isEqualToString:@"1"]) {//新建文件夹
//            type = SYCollectionViewTypeNewAddWenJianJia;
            if (self.block) {
                self.block(SYCollectionViewTypeNewAddWenJianJia, model);
            }
        }
        
        else {
            [MBProgressHUD zr_showError:@"暂不支持该类型"];
           
        }
            
        
    } else {//正常页面进来的
        if ([model.type isEqualToString:@"3"]) {//视频
            if ([self.isFrom isEqualToString:@"fenxiang"]) {
                if (self.chooseZiYuanBlock) {
                    self.chooseZiYuanBlock(model);
                }
                return;
            }
            SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
            playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
            playerVC.urlStr = model.path;
            [self.contentVC presentViewController:playerVC animated:YES completion:nil];
            return;
        }
        SYCollectionViewType type = -1;
        if (self.stant !=0) {//传入过来的数据
            type = self.stant;
        }
        
        if ([model.type isEqualToString:@"5"]) {//微课程
            type = SYCollectionViewTypeWeiKe;
        } else if ([model.type isEqualToString:@"1"]) {//新建文件夹
            type = SYCollectionViewTypeNewAddWenJianJia;
        } else if ([model.type isEqualToString:@"4"] || [model.type isEqualToString:@"6"] ||[model.type isEqualToString:@"7"] || [model.type isEqualToString:@"8"] || [model.type isEqualToString:@"9"]) { //ppt word excel 图片
            if ([self.isFrom isEqualToString:@"fenxiang"]) {
                if (self.chooseZiYuanBlock) {
                    self.chooseZiYuanBlock(model);
                }
                return;
            }
            
            
            
            SYPPTViewController *wordVC = [[SYPPTViewController alloc] init];
            wordVC.urlStr = model.path;
            wordVC.nameStr = model.titleName;
            wordVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self.contentVC presentViewController:wordVC animated:YES completion:nil];
            return;
        }
        
        if (self.block) {
            self.block(type, model);
        }
    }
    
    
    
    
}
#pragma mark - SYFunctionCollectionViewCellDelegate
//选择长按功能框得功能
- (void)selectLogPressType:(SYFunctionCollectionType)type indexPath:(NSIndexPath *)index {
    SYCollectionModel *model = self.dataArr[index.row];
    _selectModel = model;
    
    
    
    
    __weak typeof(self) weakSelf = self;
    switch (type) {
        case SYFunctionCollectionTypeDelete://删除
        {
//            [self.dataArr removeObjectAtIndex:index.row];
            
            [self requestDelete];
            
        }
            break;
        case SYFunctionCollectionTypeMobile://移动
        {
            
            [self yiDongWeiZhiQuFen];
            
        }
            break;
        case SYFunctionCollectionTypeRename://重命名
        {
            
            _alerView = [[SYNewAlerView alloc] init];
            [_alerView showAler:_alerView titleName:@"重命名" textFielPlo:@"新名字"];
            _alerView.block = ^(NSString *titleName) {//先这样写着。到时候在更改
                [weakSelf requestRenameFile:titleName collectionModel:model];
                
            };
        }
            break;
            
        case SYFunctionCollectionTypeShare://分享
            
        {
                //显示分享面板
//            [MBProgressHUD zr_showError:@"正在开发中"];

            if (self.ShareBtnClickBlock) {
                self.ShareBtnClickBlock(model);
            }
        }
            break;
        default:
            break;
    }
    
}
//-(void)WeiXIinFenXiangWIthDic:(SYCollectionModel *)model{
//    NSString *picUrl = model.fileIcon;
//    NSArray *dataArr = [picUrl componentsSeparatedByString:@","];
//    //创建网页内容对象
//    NSData * data = [[NSData alloc]init];
//    if (dataArr.count > 0) {
//        data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",dataArr[0]]]];
//    }
//    UIImage *image = [[UIImage alloc]initWithData:data];
//    if (self.detailShareStr == nil) {
//        self.detailShareStr = @"三一外语教师端";
//    }
//    WXWebpageObject *webpageObject = [WXWebpageObject object];
//    webpageObject.webpageUrl = self.sharePath;
//    WXMediaMessage *message = [WXMediaMessage message];
//    message.title = @"三一教师端";
//    message.description = model.titleName;
//    [message setThumbImage:image];
//    message.mediaObject = webpageObject;
//    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
//    req.bText = NO;
//    req.message = message;
//    req.scene = WXSceneSession;
//    [WXApi sendReq:req completion:^(BOOL success) {
//
//    }];
//}

//重命名
- (void)requestRenameFile:(NSString *)titleName collectionModel:(SYCollectionModel *)model {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:nil toView:self];
    NSString *onlySort = nil;
    if ([model.type isEqualToString:@"1"]) {//文件夹
        onlySort = @"1";
    } else {
        onlySort = @"0";
    }
    
    [SYRequestAPI zy_requestMyRenameFileFileName:titleName wjId:model.zyid onlySort:onlySort success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD zr_showError:@"命名成功"];
        [NSObject executeRunloop:^{
            if (weakSelf.block) {
                weakSelf.block(SYCollectionViewTypeAll, nil);
            }
        } afterDelay:1];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD zr_showError:error.message];
    }];
}

#pragma mark - 移动的方法
//移动
//移动位置区分 收藏，微课，文件
- (void)yiDongWeiZhiQuFen {
    if ([self.titleName isEqualToString:@"我的收藏"]) {
        [self requestWoDeShouCang];
    } else if ([self.titleName isEqualToString:@"我的作品"]) {
        [self requestWoDeWenJianYiDong];
    }
    
    
}



//我的收藏文件移动
- (void)requestWoDeShouCang {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:nil toView:self];
    if (self.typePid.length == 0) {
        self.typePid = @"0";
    }
    //查询文件夹
    [SYRequestAPI zy_resourceCollectionCollectionListPageIndex:0 pageSize:1000 sortPid:self.typePid isTinyClass:@"0" onlySort:@"1" success:^(NSMutableArray *listArr) {
        [MBProgressHUD mj_hideHUDForView:weakSelf];
        
        [weakSelf shuJuQingQiuChengGongData:listArr];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:weakSelf];
        [MBProgressHUD zr_showError:error.message];
    }];

}
//我的文件移动
- (void)requestWoDeWenJianYiDong {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:nil toView:self];
    //查询文件夹
    [SYRequestAPI zy_requestMyResourceListPageIndex:0 pageSize:1000 sortId:@"0" isTinyClass:@"0" onlySort:@"1" keyWord:@"" success:^(NSMutableArray *listArr) {
        [MBProgressHUD mj_hideHUDForView:weakSelf];
        
        [weakSelf shuJuQingQiuChengGongData:listArr];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:weakSelf];
        [MBProgressHUD zr_showError:error.message];
    }];
}




//数据请求成功需要添加战士的类
- (void)shuJuQingQiuChengGongData:(NSMutableArray *)listArr {
    self.mobileView = [[SYMobileView alloc] init];
    self.selectModel.zongFileName = self.titleName;
    [self.mobileView showAler:self.mobileView collectinModel:self.selectModel dataListArr:listArr];
    __weak typeof(self) weakSelf = self;
    //移动成功 刷新数据
    self.mobileView.block = ^{
        if (weakSelf.block) {
            weakSelf.block(SYCollectionViewTypeAll, nil);
        }
    };
}


#pragma mark - 删除
//删除
- (void)requestDelete {
    if ([self.titleName isEqualToString:@"我的收藏"]) {
        [self requestWoDeShouCangDelete];
    } else if ([self.titleName isEqualToString:@"我的作品"]) {
        [self requestWoDeWenJianDelete];
    } else if ([self.titleName isEqualToString:@"我的微课"]) {
        
    }
}

//我的收藏
- (void)requestWoDeShouCangDelete {
    [MBProgressHUD mj_showMessage:nil toView:self];
    NSString *onlySort = nil;
    if ([_selectModel.type isEqualToString:@"1"]) {//文件夹
        onlySort = @"1";
    } else {
        onlySort = @"0";
    }
    __weak typeof(self) weakSelf = self;
    NSString *stant = _selectModel.zyid;
    //删除成功会掉接口刷新
    [SYRequestAPI zy_resourceCollectionRemoveCollectionid:stant onlySort:onlySort success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUDForView:self];
        if (isSuccess) {
            [MBProgressHUD zr_showError:@"删除成功"];
            //删除成功会掉接口
            if (weakSelf.block) {
                weakSelf.block(SYCollectionViewTypeAll, nil);
            }
        }
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD zr_showError:error.message];
    }];
}

//我的文件
- (void)requestWoDeWenJianDelete {
    
    [MBProgressHUD mj_showMessage:nil toView:self];
    NSString *onlySort = nil;
    if ([_selectModel.type isEqualToString:@"1"]) {//文件夹
        onlySort = @"1";
    } else {
        onlySort = @"0";
    }
    __weak typeof(self) weakSelf = self;
    NSString *stant = _selectModel.zyid;
    
    [SYRequestAPI zy_requestMyDeleteFileId:stant onlySort:onlySort success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUDForView:self];
        if (isSuccess) {
            [MBProgressHUD zr_showError:@"删除成功"];
            //删除成功会掉接口
            if (weakSelf.block) {
                weakSelf.block(SYCollectionViewTypeAll, nil);
            }
        }
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD zr_showError:error.message];
    }];
    
    
    
}

#pragma mark 判断是否需要下载
- (void)isLoading:(NSString *)urlStr
{
    
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    _path = path;
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    if (data == nil) {//需要下载
        [self writeToCacheWithUrl:urlStr];
    } else {//不需要下载
        NSDictionary *dict = @{@"filePath":_path};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"xuanzeziyuanwangge" object:nil userInfo:dict];
    }
    
    
}
#pragma mark 写入缓存
- (void)writeToCacheWithUrl:(NSString *)urlStr
{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
    //写入路径
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    
    [data writeToFile:path atomically:YES];
    _path = path;
    [self requestdataDownLoadFile:path urlstr:urlStr];
    
}
- (void)requestdataDownLoadFile:(NSString *)filePath urlstr:(NSString *)urlStr {
    
    [MBProgressHUD mj_showMessage:@"正在下载..." toView:self];
    
    [SYDownloadFile downloadFileWithUrl:urlStr success:^(id responseObject) {
        [MBProgressHUD mj_hideHUDForView:self];
        NSDictionary *dict = @{@"filePath":filePath};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"xuanzeziyuanwangge" object:nil userInfo:dict];
        
    } failure:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [MBProgressHUD zr_showError:@"下载失败"];
        
    } progress:^(float progress, long long bytesRead) {
        // [MBProgressHUD mj_hideHUDForView:self.view];
    } savePath:filePath];
    
    
}
@end



























